from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
import sys
import requests
import json
import socket
# import fcntl
import struct
import binascii

from requests.exceptions import ConnectTimeout #自定义异常
from requests.exceptions import RequestException
from requests.exceptions import ReadTimeout

class HttpClient(QObject):
    def __init__(self):
        super().__init__()

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
    }

    token = ''

    def req(self, url, form):
        
        try:
            res = requests.post(url, data=form, headers=self.headers, timeout=(2,2))
        except ConnectTimeout as e:  #e=Exception() 定义一个异常对象
            return json.dumps({
                'code': -1000,
                'message': '连接超时',
                'data': None
            })
        except ReadTimeout as e:
            return json.dumps({
                'code': -1000,
                'message': '响应超时',
                'data': None
            })
        except RequestException as e:
            return json.dumps({
                'code': -1001,
                'message': '请求出现异常',
                'data': None
            })
        except Exception as e:
            return json.dumps({
                'code': -1002,
                'message': '未知的请求异常',
                'data': None
            })

        if(res.status_code >= 300 or res.status_code < 200):
            return json.dumps({
                'code': -1003,
                'message': '请求错误：' + res.reason,
                'data': None
            })

        return res.content.decode()
    
    def getMac(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 使用 fcntl.ioctl 函数获取网络接口的信息
        # SIOCGIFHWADDR 表示获取硬件地址信息
        # eth0 表示获取 eth0 网络接口的信息，可以根据实际情况修改
        # infoEth0 = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', b'eth0'[:15]))
        # infoWlan0 = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', b'wlan0'[:15]))
        # 将获取到的硬件地址信息转换为 MAC 地址的字符串格式
        # 使用 binascii 模块中的 b2a_hex 函数进行转换
        # mac_eth = binascii.b2a_hex(infoEth0[18:24]).decode('utf-8')
        # mac_wlan = binascii.b2a_hex(infoWlan0[18:24]).decode('utf-8')
        # 输出 MAC 地址
        # print("eth0: " + mac_eth)
        # print("wlan0: " + mac_wlan)
        # return mac_wlan
        

    @pyqtSlot()  # 注意是槽函数！
    def login(self):
        url = "https://www.jsptckdkw.cn/kw/service/counter/login"# 登录
        # mac = self.getMac()
        data={
            # "serial":"10000000a439588e"
            "serial" : "b827ebbd4cd3"
            # "serial":mac # 取消自动获取mac地址上传的注册方式
        }
        res = self.req(url, data)
        json_dict = json.loads(res)
        self.token = json_dict['data']
        self.headers['token'] = self.token

        print(json_dict)
        return json_dict

    @pyqtSlot(result=str)  # 注意是槽函数！
    def fetchTasks(self):
        url = "https://www.jsptckdkw.cn/kw/service/counter/getExamList"# 查询考试
        res = self.req(url, {})
        # json_dict = json.loads(res)
        # print(json_dict['data'])
        # return json.dumps(json_dict['data'])
        # return json_dict['data']
        return res

    @pyqtSlot(int, result=str)  # 注意是槽函数！
    def fetchPositions(self, examId):
        url = "https://www.jsptckdkw.cn/kw/service/counter/getSchoolList"#查询考点
        form = {
            "examId": examId
        }
        res = self.req(url, form)
        # json_dict = json.loads(res)
        # print(json_dict['data'])
        # return json_dict['data']
        return res

    @pyqtSlot(str, result=str)  # 注意是槽函数！
    def fetchBatchs(self, posId):
        url = "https://www.jsptckdkw.cn/kw/service/counter/getBatch"#查询批次
        form={
            "examSchoolId": posId
        }
        res = self.req(url, form)
        # json_dict = json.loads(res)
        # print(json_dict['data'])
        # return json_dict['data']
        return res

    #提交计数
    @pyqtSlot(str, str, str, int, int, result=str)
    def countSubmit(self, posId:str, batch:str, kch:int, count:int, rewrite:int):
        url = "https://www.jsptckdkw.cn/kw/service/counter/set"#上传计数
        form = {
            'examSchoolId': posId,
            'batch': batch,
            'kch': kch,
            'count': count,
            'rewrite': rewrite #0为不覆盖，1为覆盖
        }
        res = self.req(url, form)
        # json_dict = json.loads(res)
        # print(json_dict)
        # return json_dict
        return res

    @pyqtSlot(str, str, result=str)  # 注意是槽函数！
    def countQuery(self, posId:str, batch:str):
        url = "https://www.jsptckdkw.cn/kw/service/counter/getCountedList"#查询计数记录
        form={
            'examSchoolId':posId,
            'batch':batch
        }
        res = self.req(url, form)
        #json_dict = json.loads(res)
        # return json_dict['data']
        # print(res)
        return res
